Public Class CXGMainScript
{

    /*  
    Class Name: CXGMainScript
    Date: 14-April-2011   
    Requirement/Project Name: CXG   
    Requirement/Project Description: Agent Script Main Page for showing scripts with Selected Issue and Sub Issue 
    */
//All the Properties and Variables Declared below
Public Id accid{get;set;}
Public String text{get;set;}
Public String issues{get;set;}
Public String subissues{get;set;}
Public String msgtext{get;set;}
Public Issue_Subissue__c isub{get;set;}
Public DateTime enddate{get;set;}
Public string callreslution{get;set;}
Boolean flag=false;
Public Event evnt;
public string taskdisposition{get;set;}
Public String callback{get;set;}
Public Id campid {get;set;}
Public Id cmid {get;set;}
ID taskrecordtypeId;
Public CXG_Campaign_Accounts__c campaignmemb{get;set;}
Public Account contId{get;set;}
public CXGMainScript(ApexPages.StandardController stdController) {
        evnt = (Event)stdController.getRecord();
        accid=ApexPages.currentPage().getParameters().get('actid');
        cmid= ApexPages.currentPage().getParameters().get('cmid');
        campid=ApexPages.currentPage().getParameters().get('campaignid');
        issues=ApexPages.currentPage().getParameters().get('issue');
        subissues=ApexPages.currentPage().getParameters().get('subissue');
        campaignmemb=[Select Name,RecordTypeId from CXG_Campaign_Accounts__c where Id=:cmid];
        isub=[Select Script__c from Issue_Subissue__c where Issue__c=:issues AND Subissue__c=:subissues];
        contId=[Select Primary_Contact_hidden__c from Account where Id=:accid];
        }
        
    
        Public Event getEvent(){
        return evnt;
        }
        //Disposition Values
        public List<SelectOption> getDisposition() {
               List<SelectOption> options = new List<SelectOption>();
               options.add(new SelectOption('None','--None--'));
               options.add(new SelectOption('Customer Contacted','Customer Contacted'));
               return options;
               }
          //Call Resolution from Activity     
         public List<SelectOption> getCallResolution() {
               List<SelectOption> options = new List<SelectOption>();
               options.add(new SelectOption('None','--None--'));
               Schema.DescribeFieldResult fieldResult = Task.Call_Resolutions__c.getDescribe();
               List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
               for(Schema.PicklistEntry p : ple)
               options.add(new SelectOption(p.getValue(), p.getValue()));        
               return options;
               }
     
               
         Public List<ScriptSteps__c> getScriptsteps(){
         return[Select Steps_Description__c from ScriptSteps__c where Script__c=:isub.Script__c];
                }
      
         public List<SelectOption> getItems() {
                List<SelectOption> options = new List<SelectOption>(); 
                options.add(new SelectOption('Yes','Yes'));
                options.add(new SelectOption('No','No')); 
                return options; 
                }
         Public Boolean getFlag(){
         return flag;
         }          
         Public void onclickaction()  {
         if(callback=='Yes')
         flag=true;
         else
         flag=false;
         } 
         //Action Method for Saving Notes ,Disposition and Call Back Scheduled 
         Public PageReference createNote(){
         ID CxGEventRecordtypID = RecordTypeHelper.GetRecordTypeIdByDevName('Event', 'CXG_Record_Type');     
         ID CxGTaskRecordTypeID = RecordTypeHelper.GetRecordTypeIdByDevName('Task', 'CXG_Task_Layout');
         ID CxGCampaignMemberRecordTypeId = RecordTypeHelper.GetRecordTypeIdByDevName('CXG_Campaign_Accounts__c', 'Campaign_Member');         
         Notes__c notes = New Notes__c();
         notes.Account__c=accid;
         notes.Notes__c=text;
         notes.Note__c='Salesforce';
         notes.Disposition__c=taskdisposition;
         notes.Date__c=DateTime.Now();
         Task tsk = New Task(Disposition__c=taskdisposition,RecordTypeId=CxGTaskRecordTypeID,OwnerId=UserInfo.getUserId(),Campaign_Member_ID__c=campaignmemb.Name,IsContacted__c=True,CXG_Account__c=True,Description=text,Issue_Identified__c=True,Sub_Issue__c=subissues,Issue__c=issues,WhoId=contId.Primary_Contact_hidden__c,whatId=accid,ActivityDate=Date.Today(),Attempt_Date__c=DateTime.Now(),Call_Resolutions__c=callreslution,Status='Completed',Priority='Normal',Subject=callreslution);
         
         //Checking Not Null values before Submitting
         if(text==''|| taskdisposition=='None' || callreslution=='None' )
         {
            Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.WARNING,'Error-"Please fill the Notes,Disposition and Call Resolution before Submitting."','Error-“Please fill the Notes,Disposition and Call Resolution before Submitting.”' ));
         }
         DateTime newDate;
         DateTime finaldate;
         if(evnt.StartDateTime!=null)
         {
         newDate=evnt.StartDateTime;
         finaldate=newDate.addSeconds(60);
         }
         
         //Checking Call Back should not be a past date
         if(callback=='Yes'&& finaldate<DateTime.Now())
         { 
           //msgtext='Error-"Scheduled call back cannot be prior to today."';
           Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.WARNING,'Error-"Scheduled call back cannot be prior to today."','Error-“Scheduled call back cannot be prior to today.”' ));

         }
         else
         {
           Insert notes;//Inserting Notes
           Insert tsk;///Insert Task
           task insrtdTask = [select Server_URL__c from task where id = :tsk.id];
           tsk.Campaign__c=insrtdTask.Server_URL__c+cmid;
           update tsk;//Updating tasl with Campaign member URL
           Task cmnewtask= New Task(Disposition__c=taskdisposition,RecordTypeId=CxGTaskRecordTypeID,Campaign_Member_ID__c=campaignmemb.Name,IsContacted__c=True,CXG_Account__c=True,Description=text,Attempt_Date__c=DateTime.Now(),Issue_Identified__c=True,Sub_Issue__c=subissues,Issue__c=issues,whatId=cmid,ActivityDate=Date.Today(),Call_Resolutions__c=callreslution,Status='New',Priority='Normal',Subject=callreslution);
           Insert cmnewtask;
           cmnewtask.Campaign__c=insrtdTask.Server_URL__c+cmid;
           update cmnewtask;
           notes.Campaign_Link__c=insrtdTask.Server_URL__c+cmid;
           update notes;//Updation Notes with Campaign member URL
           if(evnt.StartDateTime!=null)
           {
            enddate=evnt.StartDateTime;
           }
           if(callback=='Yes' && evnt.StartDateTime!=null)
           {
           CXG_Campaign_Accounts__c cm= New CXG_Campaign_Accounts__c(Id=cmid,Call_Back_Scheduled__c=True);
           Event evt= New Event(Subject='Call Back Scheduled',Call_Back_Scheduled__c=True,Campaign_Member_ID__c=campaignmemb.Name,IsContacted__c=True,CXG_Account__c=True,RecordTypeId=CxGEventRecordtypID,Description=text,Issue_Identified__c=True,Sub_Issue__c=subissues,Issue__c=issues,WhoId=contId.Primary_Contact_hidden__c,WhatId=accid,StartDateTime=evnt.StartDateTime,IsReminderSet=True,ReminderDateTime=enddate.addMinutes(15),EndDateTime=enddate.addMinutes(30));
           Insert evt;//Inserting Events or Call backs
           evt.Campaign__c=insrtdTask.Server_URL__c+cmid;
           update evt;//Updating Event with Campaign member URL
           if(campaignmemb.RecordTypeId==CxGCampaignMemberRecordTypeId){
           Update cm;
           }
           }
           text='';
           evnt.StartDateTime=null;
           
           //Logic for CSS 60 Days  
                       
           if(taskdisposition=='Customer Contacted'){
               Account accnt= New Account(Id=accid);
               accnt.Contacted_Timestamp__c=Date.Today();
               update accnt;
                  
           }
           
           msgtext='Success-"Your note,disposition and Call Resolution have been saved to the Account Record tied to this Campaign Member.Remember once completed to move on to next call in your agent queue or on the snapshot page by clicking “Next”';
           taskdisposition='None';
           callreslution='None';
          
          }
         return null;
         }  
 }